from flask import jsonify, request, current_app, url_for, g, abort
from flask.views import MethodView
from myapp.API.v2_0 import api_v2_bp
from myapp.extensions import db
from myapp.models import Typedict, Codedict
from myapp.API.v2_0.schemas import code_schema, codes_schema

class IndexAPI(MethodView):
    def get(self):
        return jsonify({
            "api_version": "1.0",
            "api_base_url": "http://example.com/api/v1",
            "current_user_url": "http://example.com/api/v1/user",
            "authentication_url": "http://example.com/api/v1/token",
            "item_url": "http://example.com/api/v1/items/{item_id }",
            "current_user_items_url": "http://example.com/api/v1/user/items{?page,per_page}",
            "current_user_active_items_url": "http://example.com/api/v1/user/items/active{?page,per_page}",
            "current_user_completed_items_url": "http://example.com/api/v1/user/items/completed{?page,per_page}"
        })

class CodeAPI(MethodView):
    """对单个字典数据的操作"""
    def get(self, code_id=None):
        """获取指定单条记录"""
        if not code_id:
            abort(404)
        code = Codedict.query.get_or_404(code_id)
        return jsonify(code_schema(code))

    def put(self, code_id):
        """替换指定单条记录，或创建之"""
        # 获取指定记录
        code = Codedict.query.get_or_404(code_id)
        # 以新记录替换旧记录

        # 数据库保存修改
        db.session.commit()
        return '', 204

    def patch(self, code_id, **kwargs):
        """替换单条记录的更新内容"""
        # 获取指定记录
        code = Codedict.query.get_or_404(code_id)
        # 以新的键值对更新内容

        # 数据库保存修改
        db.session.commit()
        return '', 204

    def delete(self, code_id):
        """删除指定单条记录"""
        code = Codedict.query.get_or_404(code_id)
        db.session.delete(code)
        db.session.commit()
        return '', 204

    # 单元元素一般不使用POST方法


class CodesAPI(MethodView):
    """对记录集的操作"""
    def get(self,typeid=None):
        """获取指定记录集"""
        page = request.args.get('page', 1, type=int)
        per_page = current_app.config['JUDIPLAT_ITEM_PER_PAGE']

        typeid = request.args.get('typeid',type=int)
        if typeid:
            # 有字典类型id，传回符合条件的所有记录
            pagination = Codedict.query.filter(Codedict.typedict_id == typeid).paginate(page, per_page)
        else:
            # 没有类型id，传回所有字典代码数据
            # pagination = Codedict.query.all().paginate(page, per_page)
            pagination = Codedict.query.order_by(Codedict.id.desc()).paginate(page, per_page)

        items = pagination.items
        current = url_for('.codes', page=page, _external=True)
        prev = None
        if pagination.has_prev:
            prev = url_for('.codes', page=page - 1, _external=True)
        next = None
        if pagination.has_next:
            next = url_for('.codes', page=page - 1, _external=True)

        return jsonify(codes_schema(items, current, prev, next, pagination))

    def post(self):
        """在集合中创建一个新的记录，并自动生成包含在相应中"""
        pass

    def put(self, **kwargs):      # 更新某一类；否则更新整个资源
        """更新整个集合中的全部或部分用户"""
        pass

    def delete(self, **kwargs):       # 同上，有类型id时删除某一类数据集，否则删除整个资源
        """删除部分，或整个资源"""
        pass

    # 集合资源一般不使用PATCH方法





api_v2_bp.add_url_rule('/', view_func=IndexAPI.as_view('index'), methods=['GET','POST'])

code_view = CodeAPI.as_view('code')
codes_view = CodesAPI.as_view('codes')
api_v2_bp.add_url_rule('/code/', view_func=code_view, methods=['GET',])
api_v2_bp.add_url_rule('/codes/', view_func=codes_view, methods=['GET',])
api_v2_bp.add_url_rule('/codes/', view_func=codes_view, methods=['POST',])
api_v2_bp.add_url_rule('/code/<int:code_id>', view_func=code_view, methods=['GET', 'PUT', 'DELETE'])
api_v2_bp.add_url_rule('/codes/typeid=<int:typeid>', view_func=codes_view, methods=['GET', 'PUT', 'DELETE'])
